package top.xiaoshuaila.moments.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;
import top.xiaoshuaila.moments.mapper.DynamicMapper;
import top.xiaoshuaila.moments.pojo.RespBean;
import top.xiaoshuaila.moments.pojo.Users;
import top.xiaoshuaila.moments.utils.Dateutils;
import top.xiaoshuaila.moments.utils.Usersutils;

import java.io.File;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

@Service
public class DynamicServiceImpl implements DynamicService {
    @Autowired
    private DynamicMapper dynamicMapper;

    @Override
    public RespBean savedynamic(MultipartFile[] file, String text,
                                boolean selfonly) {
        System.out.println(Arrays.toString(file));
        System.out.println(text);
        System.out.println(selfonly);
        String dyid=UUID.randomUUID().toString().replace("-","");
        Users users=Usersutils.getuser();
        Timestamp time= Dateutils.getDatetime();
        String image="";
        String title=(text.length()>5?text.substring(0,5):text)+"...";
        long id= users.getId();
        for(int i=0;i< file.length;i++)
        {
            String fileName = file[i].getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf('.'));
            String newFileName = UUID.randomUUID().toString().replace("-","") + suffix;
            String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/image/";
            System.out.println(path);
            File newFile = new File(path + newFileName);
            try {
                file[i].transferTo(newFile);
            } catch (Exception e) {
                e.printStackTrace();
                RespBean.error(fileName+"图片无法保存！");
            }
            image+=",image/"+newFileName;
        }
        if(image.length()>0)image=image.substring(1);
        try {
            dynamicMapper.adddynamic(dyid,text,time,image,title,id);
            dynamicMapper.adduserdy(id,time,false,dyid,selfonly);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return RespBean.success("发布成功",true);
    }
}